<template>
    <div class="authority">
        <div class="gva-search-box">
            <el-form ref="searchForm" label-width="100" :inline="true"
            style="display: flex;flex-direction: column;align-items: center;">
                <div>
                    <el-form-item label="巡查类型">
                    <el-select v-model.number="searchInfo.type" placeholder="请选择" style="width: 300px;">
                        <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="任务名称">
                    <el-input v-model="searchInfo.name" placeholder="请输入" style="width: 300px;"/>
                </el-form-item>
                </div>
                <div>
                    <el-form-item label="巡查状态">
                    <el-select v-model.number="searchInfo.taskStatus" placeholder="请选择" style="width: 300px;">
                        <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="完成日期">
                    <el-date-picker v-model="searchInfo.time" type="daterange" range-separator="-"
                        start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                        style="width:300px" />
                </el-form-item>
                </div>
                <el-form-item>
                    <el-button type="primary" icon="search" @click="onSubmit">
                        查询
                    </el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="gva-table-box unit">
            <div class="gva-btn-list">
                <el-button type="primary" icon="download" @click="exportExcel">导出</el-button>
            </div>
            <div class="ant-alert-info">
                <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
                    <div class="pop-content">
                        <div class="pop-title">自定义列</div>
                        <div class="check-list">
                            <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </div>
                    <template #reference>
                        <div class="anticon">
                            <el-icon size="16" color="#1890ff">
                                <Setting />
                            </el-icon>
                            <div style="margin-left: 2px;">自定义列</div>
                        </div>
                    </template>
                </el-popover>
            </div>
            <el-table :data="tableData" row-key="id">
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column align="left" label="任务名称" prop="name"
                    v-if="checkedColumns.includes('任务名称')"></el-table-column>
                <el-table-column align="left" label="巡查类型" v-if="checkedColumns.includes('巡查类型')">
                    <template #default="scope">
                        <span>{{ scope.row.type == 1 ? '日常巡查' : '综合巡查' }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="巡查单位" prop="unitName" show-overflow-tooltip
                    v-if="checkedColumns.includes('巡查单位')"></el-table-column>
                <el-table-column align="left" label="巡查状态" v-if="checkedColumns.includes('巡查状态')">
                    <template #default="scope">
                        <el-tag v-if="scope.row.checkStatus == 0">待巡查</el-tag>
                        <el-tag v-if="scope.row.checkStatus == 1">巡查中</el-tag>
                        <el-tag v-if="scope.row.checkStatus == 2">已巡查</el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务下达日期" prop="name" v-if="checkedColumns.includes('任务下达日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.createdAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务开始日期" prop="name" v-if="checkedColumns.includes('任务开始日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.start) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务结束日期" prop="name" v-if="checkedColumns.includes('任务结束日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.end) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" label="任务完成日期" prop="name" v-if="checkedColumns.includes('任务完成日期')">
                    <template #default="scope">
                        {{ formatTimestamps(scope.row.completedAt) }}
                    </template>
                </el-table-column>
                <el-table-column align="left" fixed="right" label="附件" v-if="checkedColumns.includes('附件')">
                    <template #default="scope">
                        <el-button v-if="scope.row.checkStatus == 2" type="primary" link @click="editUnit(scope.row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="gva-pagination">
                <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total"
                    layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </div>
        <el-drawer v-model="dialogFormVisible" :size="1000" :before-close="handleClose" :show-close="false"
            class="sb-draw">
            <template #header>
                <div class="flex justify-between items-center">
                    <span class="text-lg">巡查详情</span>
                    <div>
                        <el-button @click="closeDialog">取消</el-button>
                    </div>
                </div>
            </template>
            <div v-for="(item,index) in taskUnitFiles" class="item">
                <div class="title" v-if="taskUnitFiles[index-1]?.system!=taskUnitFiles[index].system"> {{ item.system }}</div>
                <div> {{ item.checkOption }}</div>
                <div>检查结果: {{ item.checkResult==1?'正常':'异常' }}</div>
                <div class="imgs">
                    <img class="img" style="cursor: pointer;" v-for="img in item.pics" :src="img" alt="" @click="yulan(img)">
                </div>
                <div>检查说明: {{ item.notes }}</div>
            </div>
        </el-drawer>
        <el-dialog v-model="dialogVisible2" z-index="9999">
            <img w-full :src="dialogImageUrl2" alt="Preview Image" />
        </el-dialog>
    </div>
</template>
<script setup>
import {
    optionList,
    patrolTaskUnit,
    taskUnitReport,
    clientUnitFile,
    taskUnitExport
} from '@/api/yewuguanli'

import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { countdownEmits, ElMessage, ElMessageBox, useFormItem } from 'element-plus'
import { formatTimestamps } from '@/utils/format'

defineOptions({
    name: 'Yygl'
})
const appStore = useAppStore()
const form = ref({
    taskId: '',
    id: '',
    taskUnitFiles: []
})
const dialogVisible2 = ref(false)
const dialogImageUrl2 = ref('')
const yulan = (url) => {
    dialogVisible2.value = true
    dialogImageUrl2.value = url
}

const searchInfo = ref({
    name: '',
    time: [],
    taskStart: '',
    taskEnd: '',
    taskStatus: '',
    type: '',
    unitId:JSON.parse(localStorage.getItem('userInfo')).unitId
})
const statusList = ref([
    {
        name: '待巡查',
        id: 0
    },
    {
        name: '巡查中',
        id: 1
    },
    {
        name: '已巡查',
        id: 2
    }
])
const typeList = ref([
    {
        name: '日常巡查',
        id: 1
    },
    {
        name: '综合巡查',
        id: 2
    }
])

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
const fileList = ref([])
let validatePass = (rule, value, callback) => {
    callback()
}

const rules = reactive({
    checkResult: [{ required: true, validator: validatePass, trigger: 'blur' }],
    pictures: [{ required: true, validator: validatePass, trigger: 'blur' }],
    notes: [{ required: true, validator: validatePass, trigger: 'blur' }],
})

const yyglForm = ref(null)

const initForm = () => {
    //yyglForm.value.resetFields()
    form.value = {
        taskId: '',
        id: '',
        taskUnitFiles: []
    }
}

const checkedColumns = ref(['序号', '巡查类型', '任务名称', '巡查单位', '巡查状态', '任务下达日期','任务开始日期', '任务结束日期', '任务完成日期', '附件'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).xcjlcx) {
    checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).xcjlcx
}
const columns = ref(['序号', '巡查类型', '任务名称', '巡查单位', '巡查状态', '任务下达日期','任务开始日期', '任务结束日期', '任务完成日期', '附件'])
const handleColumnsChange = (val) => {
    let obj = {

    }
    if (localStorage.getItem('columnData')) {
        obj = JSON.parse(localStorage.getItem('columnData'))
    }
    obj.xcjlcx = val
    localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('巡查结果上报')
const addUnit = () => {
    dialogTitle.value = '巡查结果上报'
    isEdit.value = false
    dialogFormVisible.value = true
}
const closeDialog = () => {
    initForm()
    dialogFormVisible.value = false
}

const handleClose = (done) => {
    initForm()
    done()
}
const handleCurrentChange = (val) => {
    page.value = val
    getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
    const res = await patrolTaskUnit({
        pageNumber: page.value,
        pageSize: pageSize.value,
        ...searchInfo.value
    })
    if (res.code == 200) {
        tableData.value = res.result.data
        total.value = res.result.total
    }
}
getTableData()
const optionLists = ref([])
onMounted(() => {
    if (localStorage.getItem('userInfo')) {
        form.value.unitId = JSON.parse(localStorage.getItem('userInfo')).unitId
    }
    optionList().then(res => {
        optionLists.value = res.result
    })
})
const taskUnitFiles = ref([])
const enterDialog = async () => {
    let valid = true
    taskUnitFiles.value.forEach(item => {
        let imgArr = []
        item.children.forEach(m => {
            if (m.fileList.length > 0) {
                m.fileList.forEach(n => {
                    imgArr.push(n.response.result)
                })
                m.pictures = imgArr.join(',')
                imgArr = []
            } else {
                valid = false
            }
            //if(!m.)
            form.value.taskUnitFiles.push(m)
        })
        //item.pictures = item.fileList.map(m=>)
    })
    if (!valid) {
        ElMessage({
            type: 'info',
            message: '请填写完整信息'
        })
        return
    }
    taskUnitReport(form.value).then(res => {

    })
}

const editUnit = async (row) => {
    clientUnitFile({taskUnitId:row.id}).then(res=>{
         taskUnitFiles.value = res.result
         taskUnitFiles.value.forEach((item,index)=>{
            console.log(taskUnitFiles.value,index,'taskUnitFiles.value[index+1]')
            // if(taskUnitFiles.value[index+1]?.system==taskUnitFiles.value[index].system){
            //     taskUnitFiles.value[index].system=''
            // }
            item.pics = item.pictures.split(',')
         })
         console.log(taskUnitFiles.value,'taskUnitFiles.value')
         dialogFormVisible.value = true
    })
   
    // let checkOptions = row.checkOptions.split(',').map(item => Number(item))
    // let arr = []
    // console.log(checkOptions, 'checkOptions')
    // optionLists.value.forEach(item => {
    //     if (checkOptions.includes(item.id)) {
    //         item.children.forEach(m => {
    //             m.checkResult = 1
    //             m.fileList = []
    //             m.notes = ''
    //             m.system = item.name
    //             m.checkOptionId = m.id
    //             m.checkOption = m.name
    //             m.pictures = ''
    //         })
    //         arr.push(item)
    //     }
    // })
    // console.log(arr, 'arr')
    // taskUnitFiles.value = arr
    // form.value.id = row.id
    // form.value.taskId = row.taskId
    // isEdit.value = true
    // dialogTitle.value = '编辑巡查任务'
}

const onSubmit = () => {
    page.value = 1
    searchInfo.value.taskStart = searchInfo.value.time[0]
    searchInfo.value.taskEnd = searchInfo.value.time[1]
    getTableData()
}
const onReset = () => {
    page.value=1
    searchInfo.value = {
        name: '',
        time: [],
        taskStart: '',
        taskEnd: '',
        taskStatus: '',
        type: '',
        unitId:JSON.parse(localStorage.getItem('userInfo')).unitId
    }
    getTableData()
}
const uploadSuccess = (res, index1, index2) => {
    console.log(res, index1, index2, 'success')
    if (res.code != 200) {
        ElMessage({
            type: 'error',
            message: '上传失败' + res.msg
        })
        fileList.value.pop()
        return
    }
    //form.value.picture = res.result
    //yyglForm.value.validateField('ico')
}
function exportExcel(){
    taskUnitExport(searchInfo.value).then(res=>{
        if(res.code==200){
           window.open(res.result)
        }
    })
}
</script>

<style lang="scss">
.ant-alert-info {
    display: flex;
    justify-content: end;
    align-items: center;
    background-color: #e6f7ff;
    border: 1px solid #91d5ff;
    color: #1890ff;
    padding: 5px;

    .anticon {
        display: flex;
        align-items: center;
        cursor: pointer;
    }
}

.section-title {
    font-weight: bold;
    font-size: 20px;
    line-height: 33px;
    padding: 8px 0 4px 14px;
    color: #4E7DFD;
    position: relative;
}

.section-title:before {
    content: '';
    position: absolute;
    top: 17px;
    left: 0;
    width: 6px;
    height: 14px;
    border-radius: 3px;
    background: #4E7DFD;
}

.sb-draw {
    .item{
        div{
            margin: 5px 0;
        }
        .title {
            font-weight: bold;
            font-size: 18px;
            padding-bottom: 10px;
            margin-bottom: 10px;
            border-bottom: 1px solid #e4e7ed;
        }
        .imgs{
            display: flex;
            .img{
                margin-right: 8px;
                width: 100px;
                height: 100px;
            }
        }
    }
}
</style>